import { login, getAdminUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { getStore, setStore } from '../../utils/storage'

const state = {
  token: getToken(),
  name: getStore('name'),
  avatar: getStore('avatar'),
  login_time: getStore('login_time'),
  permission_role: getStore('permission_role'),
  statusCount: [],
  roles_module: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
    setStore('name', name)
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
    setStore('avatar', avatar)
  },
  SET_LOGIN_TIME: (state, login_time) => {
    state.login_time = login_time
    setStore('login_time', login_time)
  },
  SET_PERMISSION_ROLE: (state, permission_role) => {
    state.permission_role = permission_role
    setStore('permission_role', permission_role)
  },
  SET_ROLES_MODULE: (state, roles_module) => {
    state.roles_module = roles_module
    setStore('roles_module', roles_module)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        let { name, avatar, token, permission_role } = response
        commit('SET_TOKEN', token)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_PERMISSION_ROLE', permission_role)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getAdminUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const params = { token: state.token }
      getAdminUserInfo(params).then(response => {
        if (!response) {
          reject('Verification failed, please Login again.')
        }

        let { roles_module } = response

        // roles must be a non-empty array
        if (!roles_module || roles_module.length <= 0) {
          // reject('getInfo: roles must be a non-null array!')
          roles_module = ['user']
        }

        // commit('SET_ROLES', roles)
        commit('SET_ROLES_MODULE', roles_module)

        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES_MODULE', [])
      removeToken()
      resetRouter()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES_MODULE', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

